using System;
using System.IO;

namespace Boggle.Net.Model
{
    public class BasicWordList : IWordList
    {
        private readonly Trie _wordList = new Trie();

        public BasicWordList()
        {
        }

        public BasicWordList(string path) : this(path, IsWordWithinBounds)
        {
        }

        public BasicWordList(string path, Predicate<string> filter)
        {
            using (var r = new StreamReader(path))
                Load(r, filter);
        }

        #region IWordList

        public bool ContainsWord(string word)
        {
            return _wordList.Contains(word);
        }

        public bool ContainsWordStartingWith(string prefix)
        {
            return _wordList.ContainsPrefix(prefix);
        }

        #endregion

        public void Load(TextReader reader, Predicate<string> filter)
        {
            for (var word = reader.ReadLine(); word != null; word = reader.ReadLine())
            {
                var normalizedWord = word.ToUpper();

                if (filter == null || filter(normalizedWord))
                    _wordList.Add(normalizedWord);
            }
        }

        public static bool IsWordWithinBounds(string word)
        {
            return word.Length >= Game.MinimumWordLength && word.Length <= Tray.Capacity;
        }
    }
}